from flask import Flask, render_template, request, redirect, url_for, jsonify
import os
import json
import uuid
import asyncio
from novel_parser import NovelParser
from novel_tasks import process_novel, preload_next_chapter

app = Flask(__name__)

# 数据文件路径
DATA_FILE = 'novels_data.json'

# 初始化小说数据
novels = []

# 从文件加载数据
def load_data():
    global novels
    if os.path.exists(DATA_FILE):
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                novels = json.load(f)
        except Exception as e:
            print(f"加载数据失败: {e}")
            novels = []
    else:
        novels = []  # 没有初始数据

@app.route('/')
def index():
    return render_template('index.html', novels=novels)

@app.route('/novel/<int:novel_id>')
def novel_detail(novel_id):
    novel = next((n for n in novels if n['id'] == novel_id), None)
    if novel:
        return render_template('novel_detail.html', novel=novel)
    return '小说不存在', 404

@app.route('/novel/<string:novel_id>/chapter/<int:chapter_id>')
def read_chapter(novel_id, chapter_id):
    novel = next((n for n in novels if n['id'] == novel_id), None)
    if novel:
        chapter = next((c for c in novel['chapters'] if c['id'] == chapter_id), None)
        if chapter:
            # 读取章节内容
            content = read_chapter_content(novel_id,chapter['content_id'])
            # 查找上一章和下一章
            prev_chapter = next((c for c in novel['chapters'] if c['id'] == chapter_id - 1), None)
            next_chapter = next((c for c in novel['chapters'] if c['id'] == chapter_id + 1), None)

            # 启动异步任务预加载下一章节
            def run_preload_task():
                try:
                    asyncio.run(preload_next_chapter(novel_id))
                except Exception as e:
                    print(f"预加载下一章节失败: {e}")

            import threading
            thread = threading.Thread(target=run_preload_task)
            thread.daemon = True
            thread.start()
            novel['current_chapter'] = chapter_id
            return render_template('chapter.html', novel=novel, chapter=chapter, content=content, prev_chapter=prev_chapter, next_chapter=next_chapter)
    return '章节不存在', 404

@app.route('/api/add_novel', methods=['POST'])
def add_novel():
    data = request.json
    title = data.get('title')
    url = data.get('url')

    if not title or not url:
        return jsonify({'success': False, 'message': '缺少必要参数'}), 400

    # 创建新小说对象（仅包含基本信息）
    new_id = str(uuid.uuid4())
    new_novel = {
        'id': new_id,
        'title': title,
        'url': url,
        'chapters': [],  # 暂时为空，由异步任务填充
        'current_chapter': 1,
        'total_chapters': 0
    }

    # 添加到小说列表
    novels.append(new_novel)

    # 保存数据到文件
    save_data()

    # 启动异步任务后台解析存储小说内容
    def run_async_task():
        try:
            asyncio.run(process_novel(title, url, new_id, []))
        except Exception as e:
            print(f"异步任务执行失败: {e}")

    # 使用线程启动异步任务
    import threading
    thread = threading.Thread(target=run_async_task)
    thread.daemon = True
    thread.start()

    return jsonify({'success': True, 'message': '小说添加成功，正在后台解析内容', 'novel': new_novel})

# 保存小说内容到文件
def save_chapter_content(content):
    content_id = str(uuid.uuid4())
    content_dir = 'content'
    os.makedirs(content_dir, exist_ok=True)
    file_path = os.path.join(content_dir, content_id)
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return content_id
    except Exception as e:
        print(f"保存章节内容失败: {e}")
        return None

# 读取小说内容从文件
def read_chapter_content(novel_id,content_id):
    content_dir = 'content/'+novel_id
    file_path = os.path.join(content_dir, content_id)
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        print(f"读取章节内容失败: {e}")
        return '内容加载失败'

# 保存数据到文件
def save_data():
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(novels, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"保存数据失败: {e}")

if __name__ == '__main__':
    # 确保静态文件夹存在
    os.makedirs('static/images', exist_ok=True)
    # 加载数据
    load_data()
    app.run(host='0.0.0.0', port=5000, debug=False)